package com.kotlin

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.kotlin.use.bean.User
import com.kotlin.use.viewmodel.APIViewModel
import com.kotlin.use.viewmodel.RoomViewModel

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: APIViewModel
    private val roomViewModel: RoomViewModel by lazy {
        ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))[RoomViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.wanAndroid).setOnClickListener {
            viewModel = ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory(application)
            )[APIViewModel::class.java]
            viewModel.requestLogin("清河集一枝花", "xujiaqi2002.")
            viewModel.userLiveData.observe(this) {
                if (it != null) {
                    findViewById<TextView>(R.id.text).text = it.toString()
                }
            }
        }

        findViewById<Button>(R.id.add).setOnClickListener {
            val user = User("张三", 18)
            roomViewModel.insertUser(user)
        }

        findViewById<Button>(R.id.select).setOnClickListener {
           val  list = roomViewModel.loadUserList();
            findViewById<TextView>(R.id.text).text = list.toString()


        }
        findViewById<Button>(R.id.update).setOnClickListener {
            roomViewModel.updateUser("张三", 20);
        }
        findViewById<Button>(R.id.delete).setOnClickListener {
            roomViewModel.deleteUser("张三");
        }
        roomViewModel.userListLiveData.observe(this, Observer {
            if (it != null) {
                findViewById<TextView>(R.id.text).text = it.toString()
            }else{
                findViewById<TextView>(R.id.text).text = "现在没数据啦"
            }

        })
    }
}
